package com.karashi.twitter.task;

import java.util.ArrayList;
import java.util.Collections;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.karashi.R;
import com.karashi.twitter.TimelineComparator;
import com.karashi.twitter.TwitterArrayAdapter;
import com.karashi.twitter.TwitterStatus;
import com.karashi.twitter.parser.TwitterParser;

public class TweetDownloadTask extends AsyncTask<String, Void, ArrayList<TwitterStatus>> {

	private TwitterArrayAdapter adapter;
	private ArrayList<TwitterStatus> list;
	private String lang;
	private Context context;

	private ProgressDialog dialog;

	public TweetDownloadTask(TwitterArrayAdapter mTwitterArrayAdapter, ArrayList<TwitterStatus> pList, String pLang,
			Context pContext) {
		adapter = mTwitterArrayAdapter;
		list = pList;
		lang = pLang;
		context = pContext;
	}

	@Override
	protected void onPreExecute() {
		dialog = ProgressDialog.show(context, "", context.getResources().getString(R.string.dialog_msg_reflesh), true);
	}

	@Override
	protected ArrayList<TwitterStatus> doInBackground(String... urls) {

		TwitterParser parser = new TwitterParser(urls[0], lang);

		return parser.parse();
	}

	@Override
	protected void onPostExecute(ArrayList<TwitterStatus> result) {
		if (list == null) {
			list = result;
		} else {
			list.addAll(result);
		}

		Collections.sort(list, new TimelineComparator());

		adapter.notifyDataSetChanged();

		if (dialog.isShowing()) {
			dialog.dismiss();
		}
	}

}
